package com.sifou.courses.service.impl;

import com.sifou.courses.dto.SeckillGoodsDto;
import com.sifou.courses.dto.SeckillOrderDto;
import com.sifou.courses.exception.CustomException;
import com.sifou.courses.repository.entity.TSeckillGoods;
import com.sifou.courses.repository.mapper.TSeckillGoodsMapper;
import com.sifou.courses.service.ISeckillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 一般方式，并发情况会有问题
 * @author liuzhongxu
 * @date 2020/8/18
 */
@SuppressWarnings("AlibabaRemoveCommentedCode")
@Slf4j
@Service("seckillService")
public class SeckillServiceImpl implements ISeckillService {

    @Resource
    private TSeckillGoodsMapper goodsMapper;

    @Override
    public SeckillGoodsDto checkStock(Integer id) {
        TSeckillGoods tSeckillGoods = goodsMapper.selectById(id);
        if (tSeckillGoods.getCount() > 0) {
            log.debug("库存充足：count={}", tSeckillGoods.getCount());
            SeckillGoodsDto goodsDto = new SeckillGoodsDto();
            BeanUtils.copyProperties(tSeckillGoods, goodsDto);
            return goodsDto;
        }
        log.debug("库存不足：count={}", tSeckillGoods.getCount());
        throw new CustomException("库存不足");
    }

    @Override
    public Integer saleStock(SeckillGoodsDto goodsDto) {
        goodsDto.setCount(goodsDto.getCount() - 1);
        goodsDto.setSale(goodsDto.getSale() + 1);
        TSeckillGoods tSeckillGoods = new TSeckillGoods();
        BeanUtils.copyProperties(goodsDto, tSeckillGoods);
        log.debug("库存：count={} 已售：sale={}", goodsDto.getCount(), goodsDto.getSale());
        return goodsMapper.updateById(tSeckillGoods);
    }

    @Override
    public Integer rollBackStock(SeckillOrderDto orderDto) {
        TSeckillGoods tSeckillGoods = goodsMapper.selectById(orderDto.getGoodsId());
        tSeckillGoods.setCount(tSeckillGoods.getCount() + 1);
        tSeckillGoods.setSale(tSeckillGoods.getSale() - 1);
        log.debug("回滚库存成功：count={} 已售：sale={} 订单：{}", tSeckillGoods.getCount(), tSeckillGoods.getSale(), orderDto);
        return goodsMapper.updateById(tSeckillGoods);
    }
}
